import 'package:common_utils/common_utils.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:psi/base/base_controller.dart';
import 'package:psi/entity/common_resp.dart';
import 'package:psi/entity/response/purchase_item_resp.dart';
import 'package:psi/entity/response/purchase_list_resp.dart';
import 'package:psi/entity/response/purchase_statistics_resp.dart';
import 'package:psi/http/api_service.dart';
import 'package:psi/pages/home/purchase/purchase_add/purchase_add_state.dart';
import 'package:psi/routes/app_pages.dart';
import 'package:psi/utils/widget_util.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../../../entity/purchass_entity.dart';
import 'purchase_state.dart';

class PurchaseLogic extends BaseController {
  final PurchaseState state = PurchaseState();

  EasyRefreshController refreshController = EasyRefreshController(controlFinishRefresh: true, controlFinishLoad: true);

  @override
  void onReady() async {
    // TODO: implement onReady
    super.onReady();
    await getData(showLoad: true);
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  void showSearch() {
    state.showSearch.value = !state.showSearch.value;
  }

  Future<void> getStatisticsData() async {
    try {
      PurchaseStatisticsResp resp = await ApiService.request.purchaseStatistics(state.search.value);
      if (resp.code == 0) {
        state.statisticsData.value = resp.data ?? PurchaseStatisticsData();
        update(["statistics"]);
      } else {
        showToast(resp.message);
      }
    } catch (e) {
      LogUtil.e(e);
    }
  }

  Future<void> getData({num pageNumber = 1, bool showLoad = false}) async {
    try {
      if (showLoad) {
        showLoading();
      }
      getStatisticsData();
      state.search.value.pageNumber = pageNumber;
      PurchaseListResp resp = await ApiService.request.purchaseList(state.search.value);
      if (showLoad) {
        hideLoading();
      }
      if (resp.code == 0) {
        if (pageNumber == 1) {
          // 刷新
          refreshController.finishRefresh(IndicatorResult.success, true);
          state.dataSource.value = resp.data ?? PurchaseListData();
        } else {
          // 加载
          refreshController.finishLoad(IndicatorResult.success, true);
          List<PurchaseEntity>? dataSource = resp.data?.records ?? [];
          if (dataSource.isEmpty) {
            state.search.value.pageNumber = pageNumber - 1;
          }
          state.dataSource.value.records!.addAll(dataSource);
        }
        update(["top", "dataSource"]);
      } else {
        refreshController.finishRefresh(IndicatorResult.fail, true);
        refreshController.finishLoad(IndicatorResult.fail, true);
        showToast(resp.message);
      }
    } catch (e) {
      if (showLoad) {
        hideLoading();
      }
      refreshController.finishRefresh(IndicatorResult.fail, true);
      refreshController.finishLoad(IndicatorResult.fail, true);
      LogUtil.e(e);
    }
  }

  void addAction() async {
    final result = await Get.toNamed(PageNames.purchaseAdd, arguments: {"type": PurchaseType.add});
    if (result != null) {
      await getData(showLoad: true);
    }
  }

  void checkDetail(PurchaseEntity entity) async {
    final result = await Get.toNamed(PageNames.purchaseAdd, arguments: {"type": PurchaseType.detail, "data": entity});
    if (result != null) {
      int index = state.dataSource.value.records!.indexOf(entity);
      state.dataSource.value.records!.replaceRange(index, index + 1, [result]);
      update(["dataSource"]);
      await getStatisticsData();
    }

  }

  void callPhone(String? phone) async {
    if (phone != null) {
      if (RegExp(r'^1[3-9]\d{9}$').hasMatch(phone)) {
        String url = "tel: $phone";
        try {
          var result = await canLaunchUrlString(url);
          if (result) {
            await launchUrlString(url);
          }
        } catch (e) {
          LogUtil.e(e);
        }
      } else {
        logV("非手机号");
      }
    }
  }

  void clearSearch() {
    state.search.value.startTime = "";
    state.search.value.endTime = "";
    state.search.value.itemType = "";
    state.search.value.settlementType = 0;
    update(["search"]);
  }

  void unsettlementOrder(PurchaseEntity entity) {
    WidgetUtil.showInputAlert(title: "请输入已支付金额", value: entity.payAmount.toString(), valueChanged: (payAmount) {
      entity.payAmount = num.tryParse(payAmount) ?? 0;
      updateEntity(entity);
    });
  }

  void settlementOrder(PurchaseEntity entity) {
    WidgetUtil.showAlert(message: "确定结清该订单么？", onDone: () async {
      entity.payAmount = entity.realAmount;
      updateEntity(entity);
    });
  }

  void updateEntity(PurchaseEntity entity) async {
    showLoading();
    int index = state.dataSource.value.records!.indexOf(entity);
    try {
      PurchaseItemResp resp = await ApiService.request.editPurchase(entity);
      hideLoading();
      if (resp.code == 0) {
        state.dataSource.value.records!.replaceRange(index, index + 1, [resp.data!]);
        update(["dataSource"]);
        await getStatisticsData();
      } else {
        showToast(resp.message);
      }
    } catch(e) {
      hideLoading();
      showToast("服务器连接失败，请稍后再试");
    }
  }

}
